package com.crowdfunding.controller;

import com.crowdfunding.util.AjaxResult;
import com.crowdfunding.util.Page;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.nio.ch.IOUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("process")
@Controller
public class ProcessController extends BaseController{
    @Autowired
    private RepositoryService repositoryService;
    @RequestMapping("index")
    public String index(){
        return"process/index";
    }


    @RequestMapping("showimg")
    public String showimg(){
        return "process/showimg";
    }

    @ResponseBody
    @RequestMapping("doShowimgProdef")
    public void doShowimgProdef(String id, HttpServletResponse response) throws IOException {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();
        InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(resourceAsStream,outputStream);
    }
    @ResponseBody
    @RequestMapping("delete")
    public Object delete(String id){
        start();
        try{
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();
            repositoryService.deleteDeployment(processDefinition.getDeploymentId(),true);
            success(true);
        }catch (Exception e){
            e.printStackTrace();
            success(false);
        }
        return end();
    }
    @ResponseBody
    @RequestMapping("doIndex")
    public Object doIndex(@RequestParam(value = "pagesize",required = false,defaultValue = "10") Integer pagesize, @RequestParam(value = "pageno",required = false,defaultValue = "1") Integer pageno, String queryText){
        start();
        try {
            Page page=new Page(pageno,pagesize);
            //查询流程定义集合数据，可能出现了自关联，导致Jackson组建无法将集合返回
            List<ProcessDefinition> listPage = repositoryService.createProcessDefinitionQuery().listPage(page.getStartIndex(), pagesize);
            Long count = repositoryService.createProcessDefinitionQuery().count();
            page.setTotalsize(count.intValue());
            List<Map<String,Object>>myListPage=new ArrayList<>();
            for (ProcessDefinition processDefinition : listPage) {
                Map<String,Object> pd=new HashMap<>();
                pd.put("id",processDefinition.getId());
                pd.put("name",processDefinition.getName());
                pd.put("key",processDefinition.getKey());
                pd.put("version",processDefinition.getVersion());
                myListPage.add(pd);
            }
            page.setData(myListPage);
            param("page",page);
            success(true);
        }catch (Exception e){
            e.printStackTrace();
            success(false);
            message("查询流程定义失败！");
        }
        return end();
    }
    @ResponseBody
    @RequestMapping("deploy")
    public Object deploy(HttpServletRequest rs){
        AjaxResult ajaxResult=new AjaxResult();
        try{
            MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest) rs;
            MultipartFile multipartFile=multipartHttpServletRequest.getFile("processDifFile");
            String originalFilename = multipartFile.getOriginalFilename();
            //文件后缀为bpmn
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            if(ext.equals("bpmn")){
                Deployment deploy = repositoryService.createDeployment().addInputStream(originalFilename, multipartFile.getInputStream()).deploy();
                ajaxResult.setSuccess(true);
            }else{
                ajaxResult.setMessage("后缀只能是.bpmn的文件");
            }
        }catch (Exception e){
            ajaxResult.setSuccess(false);
            ajaxResult.setMessage("部署流程定义出错！");
            e.printStackTrace();
        }
        return ajaxResult;
    }

}
